/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author asmaa
 */
public class CartChanges extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    Connection conn;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //processRequest(request, response);
        HttpSession sess = request.getSession(false);
        if (sess == null) {
            response.sendRedirect("index.jsp");
        }

        Integer uid = Integer.parseInt((String) sess.getAttribute("id"));
        try {
            //processRequest(request, response);
            //request.getParameter("userId");
            PrintWriter out = response.getWriter();
            try {
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                conn = DriverManager.getConnection("jdbc:mysql://localhost/Shopping", "root", "asmaaelmasry");
            } catch (Exception ee) {
            }
            float sum = Float.parseFloat(request.getParameter("sum"));
            Statement cs = conn.createStatement();
            String cstat = "select creditLimit from User where id=" + uid;
            ResultSet crs = cs.executeQuery(cstat);
            if (crs.next()) {
                float limit;

                limit = crs.getFloat(1);
                if (limit < sum) {
                    request.setAttribute("limit", limit);
                    RequestDispatcher view = request.getRequestDispatcher("ErrorCredit.jsp");
                    view.forward(request, response);
                }
            }

            Statement s = conn.createStatement();
            String stat = "select * from Cart where status = 0 and userId=" + uid;
            ResultSet rs = s.executeQuery(stat);
            Statement s2 = conn.createStatement();
            while (rs.next()) {
                int id = rs.getInt(2);
                //out.println(id);
                String stat2 = "select Product.quantity ,Cart.quantity,price,Product.id from Product,Cart where Product.id=Cart.productId and Product.id=" + id;

                ResultSet rs2 = s2.executeQuery(stat2);
                while (rs2.next()) {
                    //out.println("rs2");
                    int pq = rs2.getInt(1);
                    int cq = rs2.getInt(2);
                    float price = rs2.getFloat(3);
                    int pID = rs2.getInt(4);
                    int totalQ = pq - cq;
                    float totallimit = cq * price;
                    //out.println(pq);
                    //out.println(cq);
                    //out.print(totalQ);
                    String sel2 = "select creditLimit from User where id=" + uid;
                    Statement sell = conn.createStatement();
                    ResultSet sel22 = sell.executeQuery(sel2);
                    while (sel22.next()) {
                        float limit = sel22.getFloat(1) - price;
                        String uplimit="update User set creditLimit="+limit+"where id="+uid;
                        Statement up=conn.createStatement();
                        up.executeUpdate(uplimit);
                        String stat3 = "update Product set quantity=" + totalQ + " where id=" + pID;
                        Statement s3 = conn.createStatement();
                        s3.executeUpdate(stat3);
                    }

                    //out.println("rs3");
                }
                String status = "update Cart set status= 1 where userId=" + uid;
                Statement stat5 = conn.createStatement();
                stat5.executeUpdate(status);
                RequestDispatcher view = request.getRequestDispatcher("BuyCart");
                view.forward(request, response);
            }
        } catch (SQLException ex) {
            Logger.getLogger(CartChanges.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
